package com.gp.shaw.netty.nio.im;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gp.shaw.netty.nio.im.model.IMMsg;
import com.gp.shaw.netty.nio.im.model.IMOperator;
import com.gp.shaw.netty.nio.im.model.IMUser;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 消息处理
 * Created by asus on 2018/11/1.
 */
public class IMHandler{
    private SocketChannel channel=null;
    private UserManager userManager=null;
    private LinkedBlockingQueue<IMMsg> queue = null;
    public IMHandler(SocketChannel channel, UserManager userManager, LinkedBlockingQueue<IMMsg> queue ){
        this.channel = channel;
        this.userManager = userManager;
        this.queue = queue;
    }

    public void doRead() {
            //TODO根据不同的操作调用不同的方法
        List<IMMsg> msgs = ReadMsg.read(channel);
        if(msgs==null||msgs.size()<=0){
            return;
        }
        for(int i = 0;i<msgs.size();i++) {
            IMMsg msg = msgs.get(i);
            try {
                todo(msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public void todo(IMMsg msg) throws InterruptedException {
        if(msg==null){
            return;
        }
        IMUser imUser = new IMUser();
        imUser.setId(msg.getSender());
        imUser.setChannel(this.channel);

        switch (msg.getOperator()) {
            case IMOperator.LOGIN:
                userManager.addUser(imUser);
                break;
            case IMOperator.LOGOUT:
                userManager.removeUser(imUser);
                break;
            case IMOperator.SEND_PERSON:
                queue.put(msg);
                break;
            case IMOperator.SEND_GROUP:
                queue.put(msg);
                break;
            case IMOperator.ADD_GROUP:
                userManager.addGroup(msg.getSender(),msg.getContent());
                break;
        }

    }

}
